package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.PageQueryVo;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-05-20
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Override
    public R<Employee> login(Employee employee , HttpServletRequest request) {
        //1.密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.获取用户名 判断是否存在并返回结果
        String username = employee.getUsername();
        Employee emp = lambdaQuery().eq(Employee::getUsername, username).one();
        if(emp == null){
            return R.error("登录失败");
        }
        //3.判断密码 判断是否相同并返回结果
        if(!password.equals(emp.getPassword())){
            return R.error("登录失败");
        }

        if(emp.getStatus() ==0){
            return R.error("账号已被禁用");
        }

        request.getSession().setAttribute("employee",emp.getId());

        return R.success(emp);
    }

    @Override
    public R<String> addEmployee(Employee employee, HttpServletRequest request) {

        //1.获取当前操作新增员工的用户id
        Long id = (Long) request.getSession().getAttribute("employee");
        //2.默认新增用户初始密码"123456",并进行md5加密并设置密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //3.设置创建和更新日期以及创建和修改用户id
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(id);
        employee.setCreateUser(id);*/

        save(employee);

        return R.success("员工添加成功!");
    }

    @Override
    public R<Page> pageQuery(PageQueryVo pageQueryVo) {
        Page<Employee> page = Page.of(pageQueryVo.getPage(), pageQueryVo.getPageSize());
        page.addOrder(new OrderItem("update_time",false));
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(pageQueryVo.getName()!=null,Employee::getName,pageQueryVo.getName());
        Page<Employee> p = page(page, wrapper);
        return R.success(p);
    }

    @Override
    public R<Object> queryByIdAndResponse(Long id) {
        Employee employee = getById(id);
        //代码健壮性判断
        if(employee!=null){
        return R.success(employee);
        }
        return R.error("没有该用户信息");
    }
}
